<template>
    <div class="wrapper">
        <top-header title="汽车保险" title-left="添加车辆" @leftClick="toAddCar"></top-header>
        <div class="wrapper">

            <bui-cell label="保险车辆" >
                <text class="car_info_input" @click="carChoose">{{selectCar.text}}</text>
            </bui-cell>
            <bui-cell label="联系人" >
                <input type="text" class="car_info_input" ref="input1" v-model="form.ownername" placeholder="请输入联系人"/>
            </bui-cell>
            <bui-cell label="联系方式" >
                <input type="number" class="car_info_input" ref="input2" max-length="11" v-model="form.ownerphone" placeholder="请输入联系方式"/>
            </bui-cell>
            <bui-cell label="身份证">
                <input type="text" class="car_info_input" ref="input3" max-length="18" v-model="form.idcardNumber" placeholder="请输入身份证号"/>
            </bui-cell>
            <div>
                <div class="car_inf_img">
                    <text class="car_info_name">身份证(正面)</text>
                    <image class="car_image" :src="form.idcard1" @click="upload(1)"></image>
                </div>
            </div>
            <div>
                <div class="car_inf_img">
                    <text class="car_info_name">身份证(反面)</text>
                    <image class="car_image" :src="form.idcard2" @click="upload(2)"></image>
                </div>
            </div>
            <div class="button">
                <wxc-button text="提交申请"
                            @wxcButtonClicked="next" :btnStyle="btnStyle"></wxc-button>
            </div>
        </div>
        <div class="side_pop" ref="side" @swipe="swipePop">
            <list>
                <cell class="cell" v-for="item in list" @click="select(item)">
                    <text class="list_cont">{{item.name}}</text>
                </cell>
            </list>
        </div>
        <am-popup
            :show.sync="isLeftShow"
            :position="position"
            :offset="offset"
            :auto-close="autoClose"
            :popup-style="style"
            width="500"
            height="900"
        >
            <list>
                <cell class="cell" v-for="item in list" @click="select(item)">
                    <text class="list_cont">{{item.brandEn}}  {{item.name}}</text>
                </cell>
            </list>
        </am-popup>
    </div>
</template>
<script>
import { WxcCheckboxList, WxcButton,wxcGridSelect } from 'weex-ui';
import { buiCell} from 'bui-weex';
const animation = weex.requireModule('animation')
import { AmPopup } from 'weex-amui';
const dateTimePicker = weex.requireModule('dateTimePicker');
import utilFunc from '../../utils/util'
import header from '../../common/header'
export default {
    components: { WxcCheckboxList, WxcButton, AmPopup,buiCell,wxcGridSelect, 
        'top-header': header, 
    },
    data () {
        return {
            token: '',
            list: [],
            btnStyle: {
                'background-color': '#1E90FF',
            },
            form: {
                'uid': '', // 用户id
                'carid': '',  // 汽车id
                'carname':'', //汽车名称
                'ownername': '',  // 车主
                'ownerphone': '',  // 车主电话
                "type":1,     //type为申请类型，1为汽车保险，2为分期购
                'idcardNumber':'',  //身份证号
                'idcard1': 'bmlocal://assets/acw/cerTop.png',  //身份证正面照
                'idcard2': 'bmlocal://assets/acw/cerBack.png', //身份证反面照
            },
            servicePage: {
                "limit": 100,
                "order": "asc",
                "page": 1,
                "sort": "id",
                "uid": '', // 100068
            },
            carList: [],
            selectCar: {
                text: '请选择保险车辆'
            },
            isLeftShow: false,
            position: 'bottom',
            offset: {},
            autoClose: true,
            style: {},
            customStyles: {
                lineSpacing: '14px',
            },
        }
    },
    created () {
        let user = this.$storage.getSync('UserInfo')
        this.servicePage.uid = user.id
        this.form.ownerphone = user.mobile
        this.form.uid = user.id
        this.getServiceCarList()
        // this.$router.getParams().then(resData => {
        //     console.log(resData)
        //     this.form.p1 = resData
        // })
    },
    mounted () {
    },
    methods: {
        // onSelect (res, { selectIndex, checked, checkedList }) {
        //     Vue.set(this, res, `本次选择的index：${selectIndex}\n是否选中：${checked
        //         ? '是'
        //         : '否'}\n选中列表：${checkedList.map(item => item.title).join(',')}`);
        // },
        goLicensePlate(){
        },
        // 上传图片
        upload (param) {
            this.blur()
            this.$image.pickAndUpload({
                allowCrop: false,             // 是否允许编辑（只有当 maxCount == 1时 此参数才会生效） 默认是false
                params: {},                  // 传递的参数
                header: {}                   // 自定义请求 header
            })
                .then(resData => {
                    console.log("uploadpic:"+resData)    // [url1, url2...]
                    switch (param) {
                        case 1:
                            this.form.idcard1 = resData[0].data.url
                            break
                        case 2:
                            this.form.idcard2 = resData[0].data.url
                            break
                    }
                }, error => {
                    console.log(error)
                    this.$notice.toast({ message: '上传失败'})
                })
        },
        // 返回
        back () {
            this.$router.back();
        },
        // 滑动事件
        swipePop (e) {
            if (e.direction == 'left') {
                this.hide()
            }
        },
        hide () {
            // this.sideAnima(-750, 800);
            this.isLeftShow = false
        },
        sideAnima (trans, time) {
            var sideEl = this.$refs.side;
            animation.transition(sideEl, {
                styles: {
                    transform: 'translateX(' + trans + 'px)',
                    transformOrigin: 'left center'
                },
                duration: time, //ms
                timingFunction: 'ease',
                delay: 0 //ms
            }, function () {
            })
        },
        select (item) {
            // this.$notice.alert({
            //     message:item
            // })
            this.selectCar.text = item.name
            this.form.carid = item.id
            this.form.carname=item.carname
            this.form.ownername = item.ownername
            this.form.ownerphone = item.ownerphone
            this.hide()
        },
        // 调取侧栏
        showSide (list) {
            this.list = list
            // this.sideAnima(750, 800);
            this.isLeftShow = true
        },
        // 封装数据
        dataPack (dataList, name) {
            for (let i = 0, length = dataList.length; i < length; i++) {
                dataList[i].name = dataList[i][name]
            }
            return dataList
        },
        //提交申请
        next () {
            if (!this.validterParam()) {
                return
            }
            const vm = this;
            var userInfo = this.$storage.getSync('UserInfo');

            this.token = userInfo.token;
            this.$fetch({
                method: 'POST',    // 大写
                name: 'maintenance.insurance.create', //当前是在apis中配置的别名，你也可以直接绝对路径请求 如：url:http://xx.xx.com/xxx/xxx
                data: this.form,
                header: {
                    'X-TMACW-APP-Token': this.token
                }
            }).then(resData => {
                // vm.$notice.alert({
                //     message:resData
                // })
                // 成功回调
                // this.isShowLoad = false;
                console.log(resData)
                if(resData && resData.errno == 0){
                    this.$notice.toast({ message: '保险申请成功，等待审核'})
                    this.back()
                }
            }, error => {
                // 错误回调
                this.isShowLoad = false;
                console.log(error)
            })

        },
        // 校验值
        validterParam () {
            if (!this.form['carid']) {
                this.$notice.toast({ message: '请选择保险车辆'})
                return false
            } else if (!this.form['ownername']) {
                this.$notice.toast({ message: '请填写联系人'})
                return false
            } else if (!this.form['ownerphone']) {
                this.$notice.toast({ message: '请填写联系方式'})
                return false
            } else if (!this.form['idcardNumber']) {
                this.$notice.toast({ message: '请填写身份证号'})
                return false
                this.$notice.toast({ message: '请上传身份证正面照片'})
                return false
            } else if (this.form['idcard2'].indexOf('cerBack.png') != -1) {
                this.$notice.toast({ message: '请上传身份证反面照片'})
                return false
            } else if (!utilFunc.checkIsHasSpecialStr(this.form['ownername'])) {
                this.$notice.toast({ message: '联系人姓名只能是汉字或字母'})
                return false
            } else if (!utilFunc.identifyReg(this.form['idcardNumber'])) {
                this.$notice.toast({ message: '身份证号格式不正确'})
                return false
            }
            return true
        },
        // 服务项目
        serviceItems (value) {
            this.form.type = value
            // this.$notice.toast({ message: this.form.type})
        },
        // 跳转添加车辆
        toAddCar () {
            this.$router.open({
                name: 'acw.service.maintennace.addcar',
                type: 'PUSH'
            });
        },
        // 查询服务车辆
        getServiceCarList () {
            this.$fetch({
                method: 'POST',    // 大写
                name: 'maintenanceCar.list', //当前是在apis中配置的别名，你也可以直接绝对路径请求 如：url:http://xx.xx.com/xxx/xxx
                data: this.servicePage
            }).then(resData => {
                // 成功回调
                console.log(resData)
                // this.$notice.toast({message: resData.data})
                if(resData && resData.errno == 0){
                    this.carList = this.dataPack(resData.data.items, 'carname')
                }
            }, error => {
                // 错误回调
                console.log(error)
            })
        },
        // 选择汽车
        carChoose() {
            this.blur()
            this.showSide(this.carList)
        },
        appoint () {
            // 示例 具体可参考demo/dateTimePicker.vue
            dateTimePicker.open({
                value: '',//必选,选中的值，格式为yyyy-MM-dd HH:mm;当value为空,默认选中当前时间;当value不为空时为返回值
                max: '',//可选，日期最大值,默认2099-12-31 23:59
                min: '',//可选，日期最小值,默认1900-12-31 00:00
                title: '',//可选，标题的文案，默认为空
                titleColor: '',//可选，默认为空,title不为空时有效，颜色值（#313131）
                confirmTitle: '', //确认按钮的文案,默认值（完成）
                confirmTitleColor: '', //确认按钮的文字颜色，默认值(#00b4ff)
                cancelTitle: '', //取消按钮的文案,默认值（取消）
                cancelTitleColor: '', //取消按钮的文字颜色,默认值(#313131)
            },(res) =>{//回调
                //返回字段
                if(res.result === "success"){
                    this.appointment.text = res.data
                    this.form.appointmentdate = res.data.split(' ')[0]
                    this.form.appointmenttime = res.data.split(' ')[1]
                }
            });
        },
        // 输入框失去焦点
        blur () {
            if (this.$refs.input1) 
                this.$refs.input1.blur()
            if (this.$refs.input2) 
                this.$refs.input2.blur()
            if (this.$refs.input3) 
                this.$refs.input3.blur()
        }
    }
}
</script>
<style>
    .iconfont {
        font-family: iconfont;
    }
    .wrapper{
        background-color: #fff;
    }
    .content{
        background-color: #fff;
        height: 1334px;
        padding-top: 100px;
    }
    .car_info{
        flex-direction: row;
        margin-top: 10px;
        margin-bottom: 10px;
        align-items: center;
    }
    .car_info_name{
        color: #666;
        width: 200px;
        text-align: center;
    }
    .car_param_val{
        flex: 1;
        flex-direction: row;
    }
    .param_val_text{
        width: 100px;
        margin-left: 20px;
        margin-right: 20px;
        padding: 10px;
        text-align: center;
        border-radius: 10px;
        border-style: solid;
        border-width: 1px;
        border-color: #aaa;
    }
    .car_info_input{
        width: 500px;
        border-style: solid;
        border-width: 1px;
        border-color: #fff;
        border-radius: 5px;
        height: 70px;
        line-height: 70px;
        padding-left: 10px;
        outline-color: #fff;
    }
    .date_div{
        flex-direction: row;
        width: 520px;
        justify-content: space-between;
    }

    .button{
        align-items: center;
        margin-top: 40px;
        margin-bottom: 40px;
    }
    .cont_car_brand {
        align-items: center;
        flex-direction: row;
        margin-top: 10px;
        margin-bottom: 10px;
    }

    .select_box{
        height: 60px;
        line-height: 60px;
        color: #666;
        margin-right: 16px;
        padding-right: 16px;
        padding-left: 16px;
    }
    .border {
        border-style: solid;
        border-width: 1px;
        border-color: #666;
        border-radius: 6px;
    }
    /* 左侧弹窗 */
    .side_pop{
        position: absolute;
        top: 138px;
        background-color: #fff;
        width: 750px;
        height: 1334px;
        padding-top: 100px;
        left: -750px;
    }
    .cell{
        width: 750px;
        border-bottom-color: #eee;
        border-bottom-style: solid;
        border-bottom-width: 1px;
    }
    .list_cont{
        color: #333;
        font-size: 30px;
        height: 100px;
        line-height: 100px;
        margin-left: 20px;
    }
    .mb10{
        margin-bottom:10px;
    }
    .pl20{
        padding-left:20px;
    }
    .car_info_name{
        color: #666;
        width: 200px;
        text-align: center;
        height: 80px;
        line-height: 80px;
    }
    .car_inf_img{
        flex-direction: row;
        margin-top: 10px;
        margin-bottom: 10px;
    }
    .car_image{
        height: 240px;
        width: 460px;
    }
</style>
